import json

from django.http import JsonResponse
from django.views import View

from role.models import SysUserRole

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework import serializers, status

from role.models import SysUserRole

# 参数校验器
class GrantRoleSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=True)
    roleIds = serializers.ListField(
        child=serializers.IntegerField(), required=True
    )


class GrantRole(APIView):
    permission_classes = [AllowAny]  # ✅ 放行，权限由中间件控制

    def post(self, request):
        serializer = GrantRoleSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {'code': 400, 'msg': '参数格式错误', 'errors': serializer.errors},
                status=status.HTTP_400_BAD_REQUEST
            )

        user_id = serializer.validated_data['id']
        role_id_list = serializer.validated_data['roleIds']

        # 删除旧角色
        SysUserRole.objects.filter(user_id=user_id).delete()

        # 批量添加新角色
        SysUserRole.objects.bulk_create([
            SysUserRole(user_id=user_id, role_id=role_id)
            for role_id in role_id_list
        ])

        return Response({'code': 200, 'msg': '角色分配成功'})